<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 加载commo vendor 下的类
 * @param $class
 * @param string $ext
 * @return bool
 */
function common_vendor($class, $ext = EXT)
{
    return \think\Loader::import($class, ROOT_PATH . "/application/common/vendor/", $ext);
}


/**
 * 压缩图片
 * @param $imgsrc
 * @return mixed
 */
function reduce_image($imgsrc)
{
    $path = sprintf("%s/public/%s", ROOT_PATH, $imgsrc);
    compressed_image($path, $path);
    #复制到 OSS
    $imgsrc_oss = $imgsrc;
    BEGIN:
    $first = substr($imgsrc_oss, 0, 1);
    if ($first == "/") {
        $imgsrc_oss = substr($imgsrc_oss, 1);
        goto BEGIN;
    }
    copy_to_oss($imgsrc_oss);
    return $imgsrc;
}

/**
 * desription 压缩图片 核心代码
 * @param sting $imgsrc 图片路径
 * @param string $imgdst 压缩后保存路径
 */
function compressed_image($imgsrc, $imgdst)
{
    list($width, $height, $type) = getimagesize($imgsrc);
    if ($width < 600 && $height < 600) {//一般尺寸不压缩
        return;
    } else if ($width > 600 && $height < 600) {//太宽的压缩
        $new_width = 600;
        $bizhi = $new_width / $width;
        $new_height = $bizhi * $height;
    } else if ($height > 600 && $width < 600) {//太高的压缩
        $new_height = 600;
        $bizhi = $new_height / $height;
        $new_width = $bizhi * $width;
    } else {
        $new_width = 600;
        $bizhi = $new_width / $width;
        $new_height = $bizhi * $height;
    }
    switch ($type) {
        case 1:
            $giftype = check_gifcartoon($imgsrc);
            if ($giftype) {
                header('Content-Type:image/gif');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $image = imagecreatefromgif($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                //75代表的是质量、压缩图片容量大小
                imagejpeg($image_wp, $imgdst, 75);
                imagedestroy($image_wp);
            }
            break;
        case 2:
            header('Content-Type:image/jpeg');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //75代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst, 75);
            imagedestroy($image_wp);
            break;
        case 3:
            header('Content-Type:image/png');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //75代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst, 75);
            imagedestroy($image_wp);
            break;
    }
}

/**
 * 复制到oss
 * @param $object
 * @return bool
 */
function copy_to_oss($object)
{
    $accessKeyId = ALI_OSS_APPID;
    $accessKeySecret = ALI_OSS_APPSECRECT;
    $endpoint = ALI_OSS_ENDPOINT;
    $bucket = ALI_OSS_BUCKET;
    $filePath = sprintf("%s/%s/%s", ROOT_PATH, "public", $object);
    $ossClient = null;
    try {
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
    } catch (\OSS\Core\OssException $e) {
        \think\Log::alert(" \\OSS\\OssClient 创建失败，配置出错；或者服务到期");
        return false;
    }
    try {
        $ossClient->uploadFile($bucket, $object, $filePath);
    } catch (\OSS\Core\OssException $e) {
        \think\Log::alert(" \\OSS\\OssClient " . $e->getMessage());
        return false;
    }
    return $object;
}


function city_name($id)
{
    $city_ = \app\common\model\City::get($id);
    return isset($city_->city_name) ? $city_->city_name : '';
}

/**
 * 树形数据
 * @param $items
 * @return array
 */
function category_to_tree($items)
{
    foreach ($items as $item)
        $items[$item['pid']]['_child'][$item['id']] = &$items[$item['id']];
    return isset($items[0]['_child']) ? $items[0]['_child'] : array();
}


function response_json($code, $data = [], $msg = '')
{
    $header = getallheaders();
    $header = isset($header["Origin"]) ? $header["Origin"] : '*';
    header('Access-Control-Allow-Credentials: true');
    header("Access-Control-Allow-Origin: {$header}");
    if (empty($msg)) {
        $msg = \app\common\Code::msg($code);
    }
    json([
        "code" => $code,
        "msg" => $msg,
        "data" => $data,
    ])->send();
    exit();
}

/**
 * 验证手机验证码
 * @param $in_phone
 * @param $in_code
 * @return bool
 */
function telephone_valid_code($in_phone, $in_code)
{
    $code = session("telephone_code");
    $phone = session("telephone_number");
    if (
        $phone == $in_phone &&
        $in_code == $code
    ) {
        return true;
    }
    return false;
}

/**
 * 发送手机验证码
 * @param $phone
 * @return int
 */
function  telephone_send_code($phone)
{
    $code = rand(1000, 9999);
    session("telephone_number", $phone);
    session("telephone_code", $code);
    \app\common\Alidayu::send($phone, "dayu_template_send", '{"code":"' . $code . '"}');
    return $code;
}

/**
 * 验证图片验证码
 * @return bool
 */
function valid_pic_capture($id = '')
{
    $data = input();
    if (isset($data["pic_captcha"])) {
        $captcha = $data["pic_captcha"];
        if (captcha_check($captcha, $id)) {
            session("SEND_PHONE_MSG_TIME", time());
            return true;
        };
    }
    return false;
}


function user_info($id){
   $user =  \app\common\model\Users::get(["id"=>$id]);
    return sprintf(
        "%s-%s",
        isset($user->user_name)?$user->user_name:'',
        isset($user->telephone)?$user->telephone:''
    );
}